<?php

namespace app\v1\logic;

use app\v1\model\AdminCity;
use app\v1\model\MiniLawyer;
use app\v1\model\MiniOrder;
use think\Db;
use think\Exception;
use think\facade\Log;

class MiniLawyerLogic
{
    public MiniLawyer $model;

    public function __construct()
    {
        $this->model = new MiniLawyer();
    }

    public function getList(array $param)
    {
        $page = [
            'page' => $param['page'] ?: 1,
            'list_rows' => $param['pageSize'] ?: 10
        ];
        $data_list = $this->model->where('status', 1)->paginate($page)->toArray();

        foreach ($data_list['data'] as $k => $v) {
            if ($v['type']) {
                $data_list['data'][$k]['type'] = explode(',', $v['type']);
            }
            if ($v['area']) {
                $data_list['data'][$k]['area'] = (new AdminCity())->getCityName($v['area']);
            }
        }
        return $data_list;
    }

    public function preOrder($param, $userId)
    {
        if (empty($param['action_id'])) return [false, '参数错误'];
        $action_id = $param['action_id'];

        // 查询律师信息
        $lawyer = $this->model->find($action_id);
        // 律师咨询价格
        if ($lawyer->price == 0) return [true, ['price' => 0, 'pay' => 0]];
        // 订单价格(抖音支付单位：分)
        $price = bcmul($lawyer->price, 100, 0);
        // 支付预下单
        $param = [
            'out_order_no' => orderNumber(),
            'subject' => "{$lawyer->name}律师在线咨询付费",
            'body' => "{$lawyer->name}律师在线咨询付费",
            'total_amount' => (int)$price
        ];

        Db::startTrans();
        try {
            // 生成订单信息
            $orderParam = [
                'order_number' => $param['out_order_no'],
                'lawyer_id' => $action_id,
                'order_total' => 1,
                'order_money' => $lawyer->price,
                'lose_time' => bcadd(time(), config('pay.order_lose_time'), 0),
                'create_user_id' => $userId
            ];
            $create = (new MiniOrder())->create($orderParam);
            // 预支付
            $dyPayResult = (new PayLogic())->dy_pay($param);

            if ($dyPayResult['err_no'] !== 0) {
                Log::write("预支付生成失败：" . json_encode($dyPayResult));
                throw new Exception('生成预支付信息失败');
            }

            // 储存预支付信息
            $create->pay_data = json_encode($dyPayResult['data']);
            $create->save();
            Db::commit();
            return [true, ['price' => $lawyer->price, 'pay' => 1, 'pay_data' => $dyPayResult['data']]];
        } catch (\Throwable $t) {
            Db::rollback();
            return [false, [$t->getFile(), $t->getLine(), $t->getMessage()]];
        }
    }
}